package cn.tedu.cake.controller;

import cn.tedu.cake.mapper.ProductMapper;
import cn.tedu.cake.pojo.dto.ProductDTO;
import cn.tedu.cake.pojo.dto.ProductUpdateDTO;
import cn.tedu.cake.pojo.entity.Product;
import cn.tedu.cake.pojo.vo.ProductByIdVO;
import cn.tedu.cake.pojo.vo.ProductVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @Author：GuoYaFeng
 * @Package：cn.tedu.cake.controller
 * @Project：cake1
 * @name：ProduckController
 * @Date：2023/3/16 18:32
 * @Filename：ProduckController
 */
@RestController
@Api(tags = "02. 商品修改管理模块")
@Validated
@RequestMapping("/product")
public class ProductController {
    @Value("${imagesPath}")
    private String dirPath;
    @Autowired(required = false)
    ProductMapper mapper;

    @PostMapping("insert")
    @ApiOperation("添加商品")
    @ApiOperationSupport(order = 100)
    public void insert(@RequestBody ProductDTO productDTO){
        System.out.println("productDTO = " + productDTO);
        Product p = new Product();
        BeanUtils.copyProperties(productDTO,p);
        p.setSaleCount(5);
        p.setViewCount(0);
        p.setCreated(new Date());
        System.out.println(p);
        mapper.insert(p);

    }

    @GetMapping("selectAdmin")
    public List<ProductVO> selectAdmin(){
        return mapper.selectAdmin();
    }
    @ApiOperation("根据ID删除商品")
    @ApiOperationSupport(order = 200)
    @PostMapping("delete")
    public void delete(int id){
        mapper.delete(id);
    }
    @PostMapping("selectUpdateById")
    public ProductByIdVO selectUpdateById(int id){
        return mapper.selectUpdateById(id);
    }

    @ApiOperation("修改商品")
    @ApiOperationSupport(order = 300)
    @PostMapping("/update")
    public void update(@RequestBody ProductUpdateDTO productUpdateDTO){
        System.out.println("productUpdateDTO = " + productUpdateDTO);
        //判断图片改了没有
        ProductByIdVO url =mapper.selectUrlById(productUpdateDTO.getId());
        if(!url.equals(productUpdateDTO.getUrl())){
            new File(dirPath+url).delete();
        }
        Product product = new Product();
        BeanUtils.copyProperties(productUpdateDTO,product);
        System.out.println(product);
        mapper.update(product);

    }



}
